package cn.newgrand.netcall.offlinefiletransfer;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.util.log.Log;

import cn.newgrand.common.NetcallUtil;

public class EmailSendingHelper {

	public static void sendEmail(String url,File file,String from,String to,String emailAddress,String methodUrl){
		JaxWsDynamicClientFactory  factory = JaxWsDynamicClientFactory.newInstance();
		Client client = factory.createClient(url);
		BufferedInputStream bytesin;
		from = NetcallUtil.getUserOrRoomName(from);
		to = NetcallUtil.getUserOrRoomName(to);
		try {
			bytesin = new BufferedInputStream(new FileInputStream(file));
			ByteArrayOutputStream bytesout = new ByteArrayOutputStream();
			
			byte[] temp = new byte[1024];      
	        int size = 0;      
	        while ((size = bytesin.read(temp)) != -1) {      
	        	bytesout.write(temp, 0, size);      
	        }      
	        bytesin.close();
	     
	        byte[] content = bytesout.toByteArray();      
			
			Object[] objs = {emailAddress,getEmailText(from,file.getName(),to),getEmailTitle(from,file.getName()),content,file.getName()};
			client.invoke(methodUrl, objs);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.error(e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.error(e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.error(e);
		}
	}
	
	public static String getEmailText(String from,String fileName,String to){
		StringBuilder sb = new StringBuilder();
		sb.append(to+"，您好！\n");
		sb.append(from+"向你发送了一个文件："+fileName+"，请查收。\n");
		sb.append("[该为系统发送的邮件，请勿回复。]");
		return sb.toString();
	}
	
	public static String getEmailTitle(String from,String fileName){
		StringBuilder sb = new StringBuilder();
		sb.append("收到"+from+"发送的文件:"+fileName+"[来自netcall系统]");
		return sb.toString();
	}
}
